package cz.ujep.ki.emap;

import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class JsonPostTask extends AsyncTask<Object, Void, Boolean> {
    public ResultListener resultListener;
    private static final String INSERT_URL = "http://ithil.ujep.cz/te/insert.php";
    
	public JsonPostTask(ResultListener listener) {
		this.resultListener = listener;
	}

	@Override
	protected Boolean doInBackground(Object... params) {
		if(params.length == 1)
			return sendMessage(toJsonString(params[0]));
		if(params.length > 1) {
			JSONArray array = new JSONArray(Arrays.asList(params));
			return sendMessage(array.toString());
		}
		return false;
	}
	
	private String toJsonString(Object object) {
		if (object instanceof JSONObject)
			return object.toString();
		if (object instanceof JSONArray)
			return object.toString();
		if (object instanceof Map)
			return (new JSONObject((Map)object)).toString();
		if (object instanceof Collection) 
			return (new JSONArray((Collection)object)).toString();
		return object.toString();
	}

	@Override
	protected void onPostExecute(Boolean result) {
		this.resultListener.onResult(result);
	}
	
	private boolean sendMessage(String msg)  {	
		Log.d("Sending", msg.toString());
		try {
	    DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(INSERT_URL);
		StringEntity se = new StringEntity(msg);
        httpost.setEntity(se);
		httpost.setHeader("Accept", "application/json");
		httpost.setHeader("Content-type", "application/json");
        HttpResponse response  = httpclient.execute(httpost);
		return response.getStatusLine().getStatusCode() < 300;
		}
		catch(Exception e) {
			return false;
		}
		
	}

}
